/**
 * Copyright 2004 Cordys R&D B.V. 
 * 
 * This file is part of the Cordys FTP Connector. 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 package com.eibus.applicationconnector.ftp;

import com.eibus.xml.nom.Node;
import com.eibus.xml.xpath.XPath;
import com.eibus.soap.fault.Fault;
import com.eibus.util.logger.CordysLogger;
import com.eibus.util.logger.Severity;
import com.eibus.applicationconnector.ftp.localization.message.Messages;

class DeleteFiles extends FTPCommand
{
	private int responseNode;
	private static final CordysLogger logger = CordysLogger.getCordysLogger(DeleteFiles.class);

	@Override
	public boolean prepare()
	{
		FTPException ftpException = null;
		
		responseNode = response.getXMLNode();
		addRequestDetailsToResponse(requestXML, responseNode);
		int filesNode = Node.getElementNS(requestXML,"files",getNameSpace());
		if(filesNode==0)
		{
			logger.log(Severity.ERROR, "<files> node is not specified in delete request.");
            Fault fault = response.createSOAPFault(Fault.Codes.CLIENT,Messages.FILES_NOT_SPECIFIED_DELETE);
            addFaultDetails2(fault.getDetail(),null,DEFAULT_QNAME,null,null);
            return false;
        }

		Node.appendToChildren(filesNode, responseNode);
		
		int[] pathNodes = XPath.getMatchingNodes("path", null, filesNode);
		if (pathNodes.length == 0)
		{	
			logger.log(Severity.ERROR, "<path> node is not specified in delete request.");
            Fault fault = response.createSOAPFault(Fault.Codes.CLIENT, Messages.FILES_NOT_SPECIFIED_DELETE);
            addFaultDetails2(fault.getDetail(), null, DEFAULT_QNAME, null, null);
            return false;
		}

		int statusNode = 0;
		int childNode = 0;
		
		for (int index = 0; index < pathNodes.length; index ++)
		{
			String path = Node.getDataWithDefault(pathNodes[index], "");
			path = getProperFileSeparator(path, true);
			try
			{
				statusNode = adapter.deleteFiles(path);
				childNode = Node.getFirstChild(statusNode);
				while (childNode != 0)
				{
					Node.appendToChildren(Node.duplicate(childNode), pathNodes[index]);	
					childNode = Node.getNextSibling(childNode);
				}
			}
			catch (FTPException e)
			{
				ftpException = e;
				if (ftpConfiguration.getProtocol().equals("SFTP"))
				{
					Node.setDataElement(pathNodes[index], "status", e.getMessage());
				}
				else
				{
					Node.setDataElement(pathNodes[index], "statuscode", e.getMessage().substring(0, 3));
					Node.setDataElement(pathNodes[index], "status", e.getMessage().substring(4));					
				}
			}
			catch (Exception ge)
			{
				logger.log(Severity.ERROR, "An exception has occured while deleting files - " + ge.getMessage(), ge);
			}
			finally
			{
				Node.delete(statusNode);
				statusNode = 0;
			}
		}
		
		if(ftpException != null)
		{
			logger.log(Severity.ERROR, "An exception has occured while deleting files - " + ftpException.getMessage(), ftpException);
			int filesNodeClone = Node.clone(filesNode, true);			
	        Fault fault = response.createSOAPFault(Fault.Codes.CLIENT, Messages.SPECIFIED_FILE_NOT_FOUND);
	        addFaultDetails2(fault.getDetail(),null,DEFAULT_QNAME,null,null);
	        fault.getDetail().addDetailEntry(filesNodeClone);
	        return false;
		}

		return true;
    }

    @Override
	public void commit()
   	{
    	/* After the command is complete, disconnect the adapter from the FTP server */
    	adapter.disconnect();
   	}
}